
#include "bsp_home_switch.h"
#include "gpio_config.h"
#include "stm32f4xx_hal.h"

/**
 * @brief Get the Home Switch Status object
 * 
 * @param serial_num 接近开关编号
 * @return home_status_t 接近开关状态
 */
home_status_t getHomeSwitchRawStatus(switch_serial_num_t serial_num)
{
    GPIO_PinState raw_status;
    
    switch (serial_num)
    {
    case FIRST_SWITCH:
        raw_status = HAL_GPIO_ReadPin(HOME_INDEX_GPIO_Port, HOME_INDEX_Pin);
        break;

    case SECOND_SWITCH:
        // raw_status = HAL_GPIO_ReadPin(HOME_INDEX2_GPIO_Port, HOME_INDEX2_Pin);
        break;

    default:
        break;
    }
    return ( raw_status == GPIO_PIN_RESET ? HOMED : AWAY);
}

/**
 * @brief Home Switch Filter Status
 * 
 * @param serial_num 接近开关编号
 * @param p_count 消抖的计数变量,指针
 * @param p_home_switch_sta 接近开关状态,指针
 */
void homeSwitchFilterStatus(switch_serial_num_t serial_num, int16_t *p_count, volatile home_status_t *p_home_switch_sta)
{
    const int16_t BOUND = 10;
    home_status_t raw_sta = getHomeSwitchRawStatus(serial_num);
    if (HOMED == raw_sta)
    {
        (*p_count)++;
        if (*p_count >= BOUND)
        {
            *p_count = BOUND;
            *p_home_switch_sta = HOMED;
        }
    }
    else
    {
        (*p_count)--;
        if (*p_count <= 0)
        {
            *p_count = 0;
            *p_home_switch_sta = AWAY;
        }
    }
}
